package com.bwhx.eruler.controller.casdilly;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.bwhx.eruler.bean.Staff;
import com.bwhx.eruler.bean.casdilly.ClothesType;
import com.bwhx.eruler.bean.casdilly.ClothesTypeModelData;
import com.bwhx.eruler.controller.BaseController;
import com.bwhx.eruler.service.casdilly.ClothesTypeService;
import com.bwhx.eruler.service.casdilly.IClothesTypeModelDataService;
import com.bwhx.eruler.util.Constant;
import com.bwhx.eruler.util.ReadExcelUtil;
import com.bwhx.eruler.util.StringUtils;

@Controller
@RequestMapping("/typemodel")
public class ClothesTypeModelDataController extends BaseController {

	@Autowired
	IClothesTypeModelDataService clothesTypeModelDataService;

	@Autowired
	ClothesTypeService clothesTypeService;

	@ResponseBody
	@RequestMapping(value = "/page.deleteclothestypemodels.ashx", method = RequestMethod.POST)
	public Map<String, String> deleteClothesTypeModelData(HttpServletRequest request, HttpServletResponse response, String categoryId,
			String typeName,
			HttpSession session) {
		java.util.HashMap<String, String> hashMap = new java.util.HashMap<>();
		String status = "-1";
		try {
			ClothesTypeModelData data = new ClothesTypeModelData();
			data.setTypeId(categoryId);
			clothesTypeModelDataService.deleteClothesTypeModelDatas(data);
			hashMap.put("msg", "删除成功");
			hashMap.put("status", "0");
		} catch (Exception ex) {
			hashMap.put("msg", ex.getMessage());
			hashMap.put("status", status);
		}

		return hashMap;
	}
	
	@ResponseBody
	@RequestMapping(value = "/page.saveclothestypemodels.ashx", method = RequestMethod.POST)
	public Map<String, String> saveClothesTypeModelData(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "fileBrow", required = false) CommonsMultipartFile file, String categoryId,
			HttpSession session) {
		java.util.HashMap<String, String> hashMap = new java.util.HashMap<>();
		String status = "-1";
		try {

			String fileName = file.getOriginalFilename();
			String extension = fileName.lastIndexOf(".") == -1 ? "" : fileName.substring(fileName.lastIndexOf(".") + 1);
			if (!"xls".equals(extension)) {
				hashMap.put("msg", "仅支持后缀为xls的Excel电子表格，若是您定的后缀为xlsx，请另存为xls！");
				hashMap.put("status", "-1");
			} else {
				if (!file.isEmpty()) {

					Staff staff = (Staff) session.getAttribute("staff");
					if (staff != null) {
						String sLoginName = staff.getsLoginName();
						// 存储在本地

						String filePath = "";
						String os = System.getProperty("os.name");
						if (os.toLowerCase().startsWith("win")) {
							filePath = String.format("%s/home/bwhx/package/huamingcexls/%s_%d_%s",
									StringUtils.GetRootPath(request), sLoginName, new Date().getTime(), fileName);
						} else {
							filePath = String.format("/home/bwhx/package/huamingcexls/%s_%d_%s", sLoginName,
									new Date().getTime(), fileName);
						}

						File ioFile = new File(filePath);
						file.transferTo(ioFile);
						List<HashMap<String, String>> datas = ReadExcelUtil.readExcel(ioFile, "号型,适用性别");
						if (datas != null && datas.size() > 0) {
							if (!datas.get(0).containsKey("error")) {
								if (clothesTypeModelDataService.insertClothesTypeModelDatas(
										getClothesTypeModelDataByHasMap(datas, categoryId))) {
									hashMap.put("msg", "导入成功");
									hashMap.put("status", "0");
								} else {
									hashMap.put("msg", "导入失败，请重试");
									hashMap.put("status", status);
								}
							} else {
								hashMap.put("msg", datas.get(0).get("error"));
								hashMap.put("status", status);
							}
						} else {
							hashMap.put("msg", "请确保xls文档的表头为 号型、适用性别，并确保文档中有号型数据");
							hashMap.put("status", status);
						}
						ioFile.delete();
					} else {
						hashMap.put("msg", "用户登录信息失效，请重新登录");
						hashMap.put("status", status);
					}
				} else {
					hashMap.put("msg", "文件无效");
					hashMap.put("status", status);
				}
			}
		} catch (Exception ex) {
			hashMap.put("msg", ex.getMessage());
			hashMap.put("status", status);
		}

		return hashMap;
	}

	private List<ClothesTypeModelData> getClothesTypeModelDataByHasMap(List<HashMap<String, String>> datas,
			String cagroryId) {
		List<ClothesTypeModelData> modelDatas = new ArrayList<ClothesTypeModelData>();
		for (int i = 0; i < datas.size(); i++) {
			ClothesTypeModelData modelData = new ClothesTypeModelData();
			modelData.setId(UUID.randomUUID().toString().replace("-", ""));
			modelData.setApplySex(datas.get(i).get("适用性别"));
			modelData.setModel(datas.get(i).get("号型"));
			modelData.setTypeId(cagroryId);
			modelData.setOrder(i);
			modelDatas.add(modelData);
		}
		return modelDatas;
	}

	@ResponseBody
	@RequestMapping(value = "/getclothestypemodels.ashx", method = RequestMethod.POST)

	public HashMap<String, Object> queryClothesTypeModels(HttpServletRequest request) {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String typeName = (String) request.getAttribute("typeName");
			String applySex = (String) request.getAttribute("applySex");
			String model = (String) request.getAttribute("model");
			if (typeName != null && applySex != null && !typeName.isEmpty() && !applySex.isEmpty()) {
				ClothesType type = new ClothesType();
				type.setTypeName(typeName);
				List<ClothesType> typies = clothesTypeService.findByCTNameAndTypeAndProjectSerial(type);
				if (typies != null && typies.size() > 0) {
					StringBuilder dataStr = new StringBuilder();
					for (int i = 0; i < typies.size(); i++) {
						dataStr.append(typies.get(i).getTypeID());
						dataStr.append(",");
					}
					dataStr.deleteCharAt(dataStr.length() - 1);
					ClothesTypeModelData data = new ClothesTypeModelData();
					data.setTypeId(dataStr.toString());
					data.setApplySex(applySex);
					if (model != null) {
						data.setModel(model);
					}
					List<ClothesTypeModelData> models = clothesTypeModelDataService
							.queryClothesTypeModelDataByTypeIdModelAndSex(data);
					resultMap.put(Constant.DATA, models);
					resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
					resultMap.put(Constant.MSG, Constant.MSG_SUCCESS);
				}
			} else {
				resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
				resultMap.put(Constant.MSG, String.format("%s，原因:参数缺失", Constant.MSG_FAIL));
			}
		} catch (Exception e) {
			resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
			resultMap.put(Constant.MSG, String.format("%s，原因:%s", Constant.MSG_FAIL, e.getMessage()));
		}
		return resultMap;
	}

	@ResponseBody
	@RequestMapping(value = "/getallclothestypemodels.ashx", method = RequestMethod.POST)
	public HashMap<String, Object> getAllClothesTypeModelByCPIDSerial(HttpServletRequest request) {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String cPIDSerial = (String) request.getAttribute("cPIDSerial");
			if (cPIDSerial == null || cPIDSerial.isEmpty()) {
				resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
				resultMap.put(Constant.MSG, String.format("%s，原因:无效的项目编号", Constant.MSG_FAIL));
			} else {
				ClothesType ct = new ClothesType();
				ct.setTypeCPIDSerial(cPIDSerial);
				List<ClothesType> clothestypes = clothesTypeService.findByClothesTypeBycPIDSerial(ct);
				if(clothestypes != null && clothestypes.size()>0) {
					for(int i=0;i<clothestypes.size();i++) {
						resultMap.put(clothestypes.get(i).getTypeName(), clothesTypeModelDataService.queryClothesTypeModelDataByTypeName(clothestypes.get(i).getTypeName()));
					}
				}
			}
		} catch (Exception ex) {
			resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
			resultMap.put(Constant.MSG, String.format("%s，原因:%s", Constant.MSG_FAIL, ex.getMessage()));
		}
		return resultMap;
	}

}
